import component from '../../core/tool/component';

/**
 * 基础组件抽象类
 * 职责：
 * 1. 定义Component层统一接口
 * 2. 纯UI逻辑，不包含业务逻辑
 * 3. 事件处理委托给Controller
 * 4. 统一状态管理
 */
export abstract class BaseComponent extends component {
    protected readonly componentName: string;
    protected isInitialized: boolean = false;
    protected playerId: string = '';

    constructor() {
        super();
        this.componentName = this.constructor.name;
    }

    /**
     * 组件初始化
     */
    init(): void {
        if (this.isInitialized) {
            console.warn(`Component ${this.componentName} already initialized`);
            return;
        }
        
        console.log(`Initializing component: ${this.componentName}`);
        this.onInit();
        this.isInitialized = true;
        console.log(`Component ${this.componentName} initialized successfully`);
    }

    /**
     * 组件销毁
     */
    destroy(): void {
        if (!this.isInitialized) {
            console.warn(`Component ${this.componentName} not initialized`);
            return;
        }
        
        console.log(`Destroying component: ${this.componentName}`);
        this.onDestroy();
        this.isInitialized = false;
        console.log(`Component ${this.componentName} destroyed successfully`);
    }

    /**
     * 设置玩家ID
     */
    setPlayerId(playerId: string): void {
        this.playerId = playerId;
    }

    /**
     * 获取玩家ID
     */
    getPlayerId(): string {
        return this.playerId;
    }

    /**
     * 检查组件是否已初始化
     */
    protected ensureInitialized(): void {
        if (!this.isInitialized) {
            throw new Error(`Component ${this.componentName} not initialized. Call init() first.`);
        }
    }

    /**
     * 子类重写此方法实现特定初始化逻辑
     */
    protected onInit(): void {
        // 默认空实现
    }

    /**
     * 子类重写此方法实现特定销毁逻辑
     */
    protected onDestroy(): void {
        // 默认空实现
    }

    /**
     * 获取组件名称
     */
    getComponentName(): string {
        return this.componentName;
    }

    /**
     * 检查组件状态
     */
    isReady(): boolean {
        return this.isInitialized;
    }

    /**
     * 日志记录方法
     */
    protected log(message: string, level: 'info' | 'warn' | 'error' = 'info'): void {
        const timestamp = new Date().toISOString();
        const logMessage = `[${timestamp}] [${this.componentName}] ${message}`;
        
        switch (level) {
            case 'info':
                console.log(logMessage);
                break;
            case 'warn':
                console.warn(logMessage);
                break;
            case 'error':
                console.error(logMessage);
                break;
        }
    }

    /**
     * 安全地显示消息
     */
    protected safeShowMessage(message: string): void {
        try {
            (this as any).say(message);
        } catch (error) {
            this.log(`Failed to show message: ${message}, Error: ${(error as any).message}`, 'error');
        }
    }

    /**
     * 安全地更新UI
     */
    protected safeUpdateUI(updateFunction: () => void, operationName: string): void {
        try {
            this.ensureInitialized();
            updateFunction();
            this.log(`UI updated successfully: ${operationName}`);
        } catch (error) {
            this.log(`UI update failed: ${operationName}, Error: ${(error as any).message}`, 'error');
        }
    }

    /**
     * 事件处理的统一包装方法
     */
    protected handleEvent<T>(
        eventHandler: () => T | Promise<T>,
        eventName: string
    ): void {
        try {
            this.ensureInitialized();
            this.log(`Handling event: ${eventName}`);
            
            const result = eventHandler();
            
            // 如果是Promise，处理异步错误
            if (result instanceof Promise) {
                result.catch((error) => {
                    this.log(`Async event handling failed: ${eventName}, Error: ${error.message}`, 'error');
                });
            }
            
        } catch (error) {
            this.log(`Event handling failed: ${eventName}, Error: ${(error as any).message}`, 'error');
        }
    }
}
